﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ODS.Config;
using ODS.Utils;
using System.IO;
using ODS.Model;
using System.Xml.Linq;
using System.Windows;

namespace ODS.WebService.DeviceFunctions
{
    public class LoadDevicesService
    {
        static bool IsAuthenticated = true;

        public static async Task<InfoResult> LoadDevices()
        {
            String url = Constants.SERVER_URL + "/devices"  ;

            InfoResult result;
            try
            {
                Stream xmlStream = await RESTfulService.HTTPGetRequest(url);

                List<DeviceModel> resultString = ParseXML(xmlStream);

                #region check authenticate
                if (!IsAuthenticated)
                {
                    InfoResult result_login = await Login_Logout.LoginService.loginService(App.userLogin.UserLoginName, App.userLogin.UserPassword);
                    if (result_login.IsSuccess)
                    {
                        if ((String)result_login.ReturnedObject == Constants.SUCCESS)
                        {
                            IsAuthenticated = true;

                            return await LoadDevices();
                        }
                        else
                        {
                            MessageBox.Show((String)result_login.ReturnedObject);
                            App.BackToLoginPage();

                        }
                    }
                    else
                    {
                        MessageBox.Show(result_login.Error);
                        App.BackToLoginPage();

                    }


                }
                #endregion

                result = new InfoResult(null, resultString);
            }
            catch (Exception ex)
            {
                result = new InfoResult(ex.Message, null);
            }
            return result;
        }

        private static List<DeviceModel> ParseXML(Stream xmlStream)
        {
            List<DeviceModel> listDeviceModel = new List<DeviceModel>();
            XDocument doc = XDocument.Load(xmlStream);

            var Authenticate = (from authen in doc.Descendants("unauthorized")
                                select new
                                {

                                }).FirstOrDefault();
            if (Authenticate != null)
            {
                IsAuthenticated = false;
                return null;
            }

            var devices = from device in doc.Descendants("deviceDetails")
                            select new
                            {
                                ExpiresAt = device.Element("expiresAt").Value,
                                IMEI = device.Element("imei").Value,
                                MSISDN = device.Element("msisdn").Value,
                                Name = device.Element("name").Value,
                                Requests = device.Element("requests").Value,
                                     
                            };
            foreach (var device in devices)
            {
                DeviceModel deviceModel = new DeviceModel();
                deviceModel.ExpiresAt = CommonUtil.ParseDateTimeFromString(device.ExpiresAt);
                deviceModel.DeviceIMEI = device.IMEI;
                deviceModel.DevicePhoneNumber = device.MSISDN;
                deviceModel.VehicleName = device.Name;
                deviceModel.RemainingRequestNumber = device.Requests;

                listDeviceModel.Add(deviceModel);
            }


            return listDeviceModel;
        }
    }
}
